<script setup lang="ts">
defineOptions({ name: "deviceInfo" });

import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import axios from "axios";
import type { FormRules, FormInstance } from "element-plus";
import type { RuleType } from "async-validator";
import { QuestionFilled } from "@element-plus/icons-vue";
/** ========= API 地址 =========
 * 后端路由对应：
 *  GET  /api/customer-device-info/query
 *  POST /api/customer-device-info/add
 *  PUT  /api/customer-device-info/updateByDevice/{device}
 *  DELETE /api/customer-device-info/deleteByDevice/{device}
 * 如与你的后端不同，请在此处调整。
 */
// const API_BASE = "https://localhost:44389/api/shipment";
const API_BASE = "http://10.20.5.21:8080/api/shipment";
const API_URL_ADD = `${API_BASE}/deviceInfo/add`;
const API_URL_QUERY = `${API_BASE}/deviceInfo/query`;
const API_URL_DEL = `${API_BASE}/deleteByDevice`;
const API_URL_EDIT = `${API_BASE}/updateByDevice`; // 需要拼接 /{device}

// ========== Dialog 与表单 ==========
const dialogVisible = ref(false);
const formRef = ref<FormInstance | null>(null);
const editFormRef = ref<FormInstance | null>(null);
let loadingInstance: any = null;

type FormModel = {
  customerCode: string;
  groupCode: string;
  device: string;
  ownerName: string;
  ownerEmail: string;
};
// 新增表单
const formData = reactive<FormModel>({
  customerCode: "",
  groupCode: "",
  device: "",
  ownerName: "",
  ownerEmail: ""
});

// 责任人列表
const ownerList = [
  "董小勇",
  "朱俊",
  "李明珠",
  "居校红",
  "张瑞杨",
  "赵宏锐",
  "刘浩",
  "朱思腾",
  "胡金涛",
  "黄嘉辰",
  "崔佳庆",
  "孙娜",
  "伍海龙",
  "杨振宁",
  "詹锦琦",
  "卞豆豆",
  "李唐洋",
  "严正江",
  "无"
];

// 校验规则
const emailType: RuleType = "email";

const rules: FormRules<FormModel> = {
  customerCode: [
    { required: true, message: "请输入 Customer Code", trigger: "blur" },
    { max: 50, message: "不能超过 50 个字符", trigger: "blur" }
  ],
  groupCode: [{ max: 50, message: "不能超过 50 个字符", trigger: "blur" }],
  device: [
    { required: true, message: "请输入 Device（唯一）", trigger: "blur" }
  ],
  ownerName: [{ max: 100, message: "不能超过 100 个字符", trigger: "blur" }],
  ownerEmail: [
    { type: emailType, message: "邮箱格式不正确", trigger: "blur" },
    { max: 200, message: "不能超过 200 个字符", trigger: "blur" }
  ]
};

const openDialog = () => {
  dialogVisible.value = true;
};

// ========== 列表数据 & 查询 ==========
type RowDto = {
  customerCode?: string | null;
  groupCode?: string | null;
  device?: string;
  ownerName?: string | null;
  ownerEmail?: string | null;
  createdAt?: string | null;
  updatedAt?: string | null;
};

const tableData = ref<RowDto[]>([]);
const searchParams = reactive({
  customerCode: "",
  groupCode: "",
  device: "",
  ownerName: ""
});
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);

const fetchData = async () => {
  try {
    const { data } = await axios.get(API_URL_QUERY, {
      params: {
        ...searchParams,
        page: page.value,
        pageSize: pageSize.value
      }
    });
    tableData.value = data.items || [];
    total.value = data.total || 0;
  } catch (error: any) {
    console.error("数据加载失败:", error);
    ElMessage.error(error?.message || "数据加载失败");
  }
};

const resetSearch = () => {
  searchParams.customerCode = "";
  searchParams.groupCode = "";
  searchParams.device = "";
  searchParams.ownerName = "";
  page.value = 1;
  fetchData();
};

const handlePageChange = async (newPage: number) => {
  page.value = newPage;
  await fetchData();
};

const handleSizeChange = async (newSize: number) => {
  pageSize.value = newSize;
  await fetchData();
};

// ========== 新增 ==========
const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      ElMessage.error("表单填写不正确");
      return;
    }
    try {
      const resp = await axios.post(API_URL_ADD, formData);
      if (resp && resp.status >= 200 && resp.status < 300) {
        ElMessage.success("保存成功");
        dialogVisible.value = false;
        formRef.value.resetFields();
        await fetchData();
      } else {
        ElMessage.error("保存失败！");
      }
    } catch (error: any) {
      ElMessage.error(
        error?.response?.data?.message || error?.message || "保存失败"
      );
    }
  });
};

// ========== 编辑 ==========
const editdialogVisible = ref(false);
const editData = reactive<FormModel>({
  customerCode: "",
  groupCode: "",
  device: "",
  ownerName: "",
  ownerEmail: ""
});

const editRecord = (row: RowDto) => {
  Object.assign(editData, row);
  editdialogVisible.value = true;
};

const updateRecord = () => {
  editFormRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      ElMessage.error("表单填写不正确");
      return;
    }
    try {
      // 以 DEVICE 作为唯一键，后端路由 /updateByDevice/{device}
      const resp = await axios.put(
        `${API_URL_EDIT}/${encodeURIComponent(editData.device || "")}`,
        {
          customerCode: editData.customerCode,
          groupCode: editData.groupCode,
          ownerName: editData.ownerName,
          ownerEmail: editData.ownerEmail
        }
      );
      if (resp && resp.status >= 200 && resp.status < 300) {
        ElMessage.success("更新成功");
        editdialogVisible.value = false;
        await fetchData();
      } else {
        ElMessage.error("更新失败");
      }
    } catch (error: any) {
      ElMessage.error(
        error?.response?.data?.message || error?.message || "更新失败"
      );
    }
  });
};

// ========== 删除 ==========
const deleteRecord = async (device: string) => {
  if (!device) return;
  ElMessageBox.confirm("确认删除此记录？", "警告", { type: "warning" })
    .then(async () => {
      try {
        await axios.delete(`${API_URL_DEL}/${encodeURIComponent(device)}`);
        ElMessage.success("删除成功");
        await fetchData();
      } catch (error: any) {
        ElMessage.error(
          error?.response?.data?.message || error?.message || "删除失败"
        );
      }
    })
    .catch(() => {});
};

// 演示图片逻辑：保留
const showPreview2 = ref(false);
const srcList2 = ["/tezehngdain.png"];
const showPreview3 = ref(false);
const srcList3 = ["/guangban.png"];

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div>
    <div class="dark:header-container">
      <el-form class="search-form">
        <el-form-item label="客户代码">
          <el-input
            v-model="searchParams.customerCode"
            placeholder="输入 Customer Code"
            clearable
          />
        </el-form-item>
        <el-form-item label="集团代码">
          <el-input
            v-model="searchParams.groupCode"
            placeholder="输入 Group Code"
            clearable
          />
        </el-form-item>
        <el-form-item label="Device">
          <el-input
            v-model="searchParams.device"
            placeholder="输入 Device"
            clearable
          />
        </el-form-item>
        <el-form-item label="责任人">
          <el-select
            v-model="searchParams.ownerName"
            placeholder="选择负责人"
            clearable
            filterable
          >
            <el-option
              v-for="item in ownerList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="openDialog">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div style="width: 100%; overflow-x: auto">
      <el-table
        :data="tableData"
        border
        style="min-width: 1100px"
        :fit="true"
        class="custom-table"
        row-key="device"
      >
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button size="small" @click="editRecord(row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteRecord(row.device!)"
              >删除</el-button
            >
          </template>
        </el-table-column>

        <el-table-column
          prop="customerCode"
          label="客户代码"
          min-width="150"
          sortable
        />
        <el-table-column
          prop="groupCode"
          label="集团代码"
          min-width="150"
          sortable
        />
        <el-table-column
          prop="device"
          label="Device"
          min-width="180"
          sortable
        />
        <el-table-column
          prop="ownerName"
          label="责任人"
          min-width="160"
          sortable
        >
          <template #default="{ row }">
            <el-tag effect="dark"> {{ row.ownerName || "无" }} </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ownerEmail" label="邮箱" min-width="220" />
      </el-table>
    </div>

    <div class="example-pagination-block">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增 -->
    <el-dialog v-model="dialogVisible" title="新增记录" width="600px">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="客户代码" prop="customerCode">
          <el-input v-model="formData.customerCode" maxlength="50" />
        </el-form-item>
        <el-form-item label="集团代码" prop="groupCode">
          <el-input v-model="formData.groupCode" maxlength="50" />
        </el-form-item>
        <el-form-item label="Device" prop="device">
          <el-input v-model="formData.device" maxlength="100" />
        </el-form-item>
        <el-form-item label="责任人" prop="ownerName">
          <el-input v-model="formData.ownerName" maxlength="100" />
        </el-form-item>
        <el-form-item label="邮箱" prop="ownerEmail">
          <el-input v-model="formData.ownerEmail" maxlength="200" />
        </el-form-item>
      </el-form>

      <el-icon><QuestionFilled /></el-icon>
      <div class="form-note">新增时 DEVICE 必须唯一；邮箱需为有效格式。</div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog v-model="editdialogVisible" title="编辑记录" width="600px">
      <el-form
        ref="editFormRef"
        :model="editData"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="客户代码" prop="customerCode">
          <el-input v-model="editData.customerCode" maxlength="50" />
        </el-form-item>
        <el-form-item label="集团代码" prop="groupCode">
          <el-input v-model="editData.groupCode" maxlength="50" />
        </el-form-item>
        <el-form-item label="Device" prop="device">
          <!-- 以 Device 为主键更新，避免误改，禁用编辑 -->
          <el-input v-model="editData.device" disabled />
        </el-form-item>
        <el-form-item label="责任人" prop="ownerName">
          <el-input v-model="editData.ownerName" maxlength="100" />
        </el-form-item>
        <el-form-item label="邮箱" prop="ownerEmail">
          <el-input v-model="editData.ownerEmail" maxlength="200" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editdialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateRecord">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.form-note {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
  margin-left: 20px;
}

.header-container {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 16px;
  background: #fff;
  margin-bottom: 20px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;

  .el-form-item {
    margin-bottom: 0;

    .el-input {
      width: 180px;
      transition: all 0.3s;

      &:hover .el-input__wrapper {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
    .el-form-item__label {
      color: #606266;
      font-weight: 500;
    }
  }
}

.el-table {
  margin: 20px 0;
  border-radius: 8px;
  overflow: hidden;

  th.el-table__cell {
    background: #f8f9fa;
    color: #606266;
    font-weight: 600;
  }

  .el-button {
    margin-right: 8px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.example-pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;

  .el-pagination {
    padding: 8px 16px;
    background: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.el-form {
  .el-form-item {
    margin-bottom: 18px;

    .el-input__wrapper {
      transition: all 0.3s;
      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }
      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }

  .is-required .el-form-item__label::before {
    color: #f56c6c;
    margin-right: 4px;
  }
}
</style>
